package com.foreveross.fetl.core.domain.freight.repository.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.mortbay.log.Log;
import org.springframework.stereotype.Repository;

import com.foreveross.fetl.common.HBaseTable;
import com.foreveross.fetl.common.hbase.client.HBaseHelper;
import com.foreveross.fetl.common.jpa.EntityHibernateRepository;
import com.foreveross.fetl.common.vo.ReturnDoublePlaneInfo;
import com.foreveross.fetl.core.domain.freight.AirChinaInternationalEntity;
import com.foreveross.fetl.core.domain.freight.repository.IAirChinaInternationalRepository;
import com.foreveross.fetl.core.domain.task.SourceEntity;
import com.foreveross.fetl.util.DateUtils;
import com.foreveross.fetl.util.RowkeyUtils;
import com.foreveross.fetl.util.StringUtils;

@Repository("airChinaInternationalRepository")
public class AirChinaInternationalRepositoryImpl extends
		EntityHibernateRepository implements IAirChinaInternationalRepository {

	List<String> listCarrierKey = new ArrayList<String>();

	@Override
	public List<AirChinaInternationalEntity> findByCondition(Date reportDate,
			Date flightDate, String fromCityCode, String toCityCode,
			String flightNo, String carrierKey, String hbaseKey) {
		StringBuffer jpql = new StringBuffer(
				"select airChina from AirChinaInternationalEntity airChina where 1=1 ");
		List<Object> conditionVals = new ArrayList<Object>();
		if (reportDate != null) {
			jpql.append(" and airChina.reportDate =? ");
			conditionVals.add(reportDate);
		}
		if (flightDate != null) {
			jpql.append(" and airChina.flightDate =? ");
			conditionVals.add(flightDate);
		}
		if (null != fromCityCode && !"".equals(fromCityCode)) {
			jpql.append(" and airChina.fromCityCode =? ");
			conditionVals.add(fromCityCode);
		}
		if (null != toCityCode && !"".equals(toCityCode)) {
			jpql.append(" and airChina.toCityCode =? ");
			conditionVals.add(toCityCode);
		}
		if (null != flightNo && !"".equals(flightNo)) {
			jpql.append(" and airChina.flightNo =? ");
			conditionVals.add(flightNo);
		}
		if (null != hbaseKey && !"".equals(hbaseKey)) {
			jpql.append(" and airChina.hbaseKey =? ");
			conditionVals.add(hbaseKey);
		}
		if (null != carrierKey && !"".equals(carrierKey)) {
			jpql.append(" and airChina.carrierKey =? ");
			conditionVals.add(carrierKey);
		}

		jpql.append(" order by airChina.createTime desc ");
		return super.queryResult(jpql.toString(), conditionVals.toArray());
	}

	@Override
	public int creatReport(List<String> airCompanys, String fromCity,
			String toCity, Date reportDate, Date flightDate) {
		List<AirChinaInternationalEntity> listAir = new ArrayList<AirChinaInternationalEntity>();

		for (String channel : airCompanys) {
			SourceEntity sourceEntity = new SourceEntity();
			if (channel.startsWith("2")) {
				List<SourceEntity> listSource = sourceEntity
						.findByHbaseKey(channel);
				if (null != listSource && listSource.size() > 0) {
					listCarrierKey.add(listSource.get(0).getCarrierKey());
				}
			}
		}
		Map<String, List<AirChinaInternationalEntity>> map = new HashMap<String, List<AirChinaInternationalEntity>>();
		for (String channel : airCompanys) {
			map.put(channel, this.build(channel, fromCity, toCity, reportDate,
					flightDate));
		}
		List<AirChinaInternationalEntity> tempair = null;
		for (String channel : airCompanys) {
			tempair = map.get(channel);
			if (null == tempair) {
				continue;
			}
			for (AirChinaInternationalEntity en : tempair) {
				listAir.add(en);
			}
		}
		return this.saveList(listAir);
	}

	private List<AirChinaInternationalEntity> build(String channel,
			String fromCity, String toCity, Date reportDate, Date flightDate) {
		String startRowKey = RowkeyUtils.getRowKey(reportDate, channel,
				fromCity, toCity, flightDate, RowkeyUtils.START_ROW_KEY);
		String endRowKey = RowkeyUtils.getRowKey(reportDate, channel, fromCity,
				toCity, flightDate, RowkeyUtils.STOP_ROW_KEY);
		ResultScanner rs = null;
		List<AirChinaInternationalEntity> listEntity = new ArrayList<AirChinaInternationalEntity>();
		try {
			rs = HBaseHelper.getRecords(HBaseTable.BASE_DATA_FLIGHT_DOUBLE,
					startRowKey, endRowKey);
			for (Result res : rs) {
				List<AirChinaInternationalEntity> list = this.buildAirSpread(
						res, channel, reportDate, flightDate);
				if (null == list || list.size() == 0) {
					continue;
				}
				for (AirChinaInternationalEntity en : list) {
					listEntity.add(en);
				}
			}
		} catch (IOException e) {
			Log.info(StringUtils.getStackTrace(e));
		} finally {
			if (rs != null)
				rs.close();
			rs = null;
		}
		return listEntity;
	}

	private List<AirChinaInternationalEntity> buildAirSpread(Result res,
			String channel, Date reportDate, Date flightDate) {
		Map<String, Map<String, String>> curMap = HBaseHelper
				.transformHBaseRowToMap(res);

		if (curMap.containsKey("transitsInfo") && curMap.get("transitsInfo").containsKey("flightNo_1"))
			return null; // 不要中转

		Map<String, String> curPalneInfoMap = curMap.get("planeinfo");

		String flightNo = curPalneInfoMap.get("flightId");
		String carrierKey = flightNo.substring(0, 2);

		if (!listCarrierKey.contains(carrierKey)) {
			return null; // 其它航空公司的航班不要
		}

		if (!curMap.containsKey("returnPlaneInfosInfo")) {
			return null; // 返程为空不要
		}

		// 返程
		List<ReturnDoublePlaneInfo> doublePlaneInfos = new ArrayList<ReturnDoublePlaneInfo>();
		doublePlaneInfos = this
				.getReturnDoublePlaneInfoList(curMap, carrierKey);
		if (null == doublePlaneInfos)
			return null;

		List<AirChinaInternationalEntity> listAirChina = new ArrayList<AirChinaInternationalEntity>();
		for (ReturnDoublePlaneInfo vo : doublePlaneInfos) {
			AirChinaInternationalEntity entity = new AirChinaInternationalEntity();
			entity.setCarrierKey(carrierKey);
			entity.setHbaseKey(channel);
			entity.setFromCityCode(curPalneInfoMap.get("fromCity"));
			entity.setToCityCode(curPalneInfoMap.get("toCity"));
			entity.setFromCityName(curPalneInfoMap.get("fromCityName"));
			entity.setToCityName(curPalneInfoMap.get("toCityName"));
			entity.setReportDate(DateUtils.parse(
					DateUtils.format(reportDate, "yyyyMMdd"), "yyyyMMdd"));
			entity.setFlightDate(DateUtils.parse(
					DateUtils.format(flightDate, "yyyyMMdd"), "yyyyMMdd"));
			entity.setCreateTime(new Date());
			entity.setFlightNo(flightNo + "-" + vo.getFlightNo());
			entity.setPrice(vo.getTotalLowestPrice());
			listAirChina.add(entity);
		}

		return listAirChina;
	}

	private List<ReturnDoublePlaneInfo> getReturnDoublePlaneInfoList(
			Map<String, Map<String, String>> curMap, String carrierKey) {

		int max = 0;
		Map<String, String> fcv = curMap.get("returnPlaneInfosInfo");
		for (String key : fcv.keySet()) {
			if (key.startsWith("flightId") || key.startsWith("sumLowerPrice")) {
				String[] strs = key.split("_");
				if (!isNumeric(strs[strs.length - 1])) {
					continue;
				}
				int num = Integer.parseInt(strs[strs.length - 1]);
				if (num > max) {
					max = num;
				}
			}
		}

		List<ReturnDoublePlaneInfo> list = new ArrayList<ReturnDoublePlaneInfo>();
		for (int i = 0; i < max + 1; i++) {

			String flightno = fcv.get("flightId_" + i);
			if (null == flightno) {
				continue;
			}

			if (curMap.containsKey("returnTransitsInfo")) {
				Map<String, String> transMap = curMap.get("returnTransitsInfo");
				if(transMap.containsKey("flightNo_" + i + "_1"))
					continue;// 不要中转
//				if (transMap.get("flightNo_" + i + "_0") != null) {
//					continue;// 不要中转
//				}
			}

			ReturnDoublePlaneInfo vo = new ReturnDoublePlaneInfo();
			vo.setFlightNo(flightno);
			if (!vo.getFlightNo().startsWith(carrierKey)) {
				continue;// 只要相应航空公司的航班
			}
			vo.setTotalLowestPrice(Double.parseDouble(fcv.get("sumLowerPrice_"
					+ i) != null ? fcv.get("sumLowerPrice_" + i) : "0"));
			list.add(vo);

		}

		return list;
	}

	private int saveList(List<AirChinaInternationalEntity> list) {
		if (null != list && list.size() > 0) {
			int i = 0;
			for (AirChinaInternationalEntity entity : list) {
				List<AirChinaInternationalEntity> oldList = new ArrayList<AirChinaInternationalEntity>();
				entity.setCreateTime(new Date());
				oldList = this.findByCondition(entity.getReportDate(),
						entity.getFlightDate(), entity.getFromCityCode(),
						entity.getToCityCode(), entity.getFlightNo(), null,
						entity.getHbaseKey());
				if (null != oldList && !oldList.isEmpty()) {
					AirChinaInternationalEntity oldEntity = oldList.get(0);
					entity.setId(oldEntity.getId());
				}
				this.save(entity);
				i++;
			}
			return i;
		}
		return 0;
	}

	private boolean isNumeric(String str) {
		return str.matches("\\d*");
	}

}
